"""
Image processing utilities for handling image format, size and dimensions
"""

import logging
import os

from PIL import Image

logger = logging.getLogger(__name__)


def compress_image(image_path: str, max_size_kb: int = 2048) -> bool:
    """Compress image to meet size requirements

    Args:
        image_path: Path to the image file
        max_size_kb: Maximum allowed size in KB (default 2MB)

    Returns:
        bool: True if compression was successful
    """
    try:
        # 获取原始文件大小
        original_size = os.path.getsize(image_path)
        if original_size <= max_size_kb * 1024:
            return True  # 已经符合大小要求

        with Image.open(image_path) as img:
            # 保存原始格式
            format = img.format

            # 计算初始质量
            quality = 95

            while True:
                # 创建临时文件名
                temp_path = f"{image_path}.temp"

                # 保存压缩后的图片
                img.save(temp_path, format=format, quality=quality)

                # 检查新文件大小
                new_size = os.path.getsize(temp_path)

                if new_size <= max_size_kb * 1024:
                    # 压缩成功，替换原文件
                    os.replace(temp_path, image_path)
                    logger.info(
                        f"图片压缩成功: {image_path} "
                        f"({original_size/1024:.1f}KB -> {new_size/1024:.1f}KB)"
                    )
                    return True

                if quality <= 30:
                    # 质量已经很低，仍然无法达到目标大小
                    os.remove(temp_path)
                    logger.error(f"无法将图片压缩到目标大小: {image_path}")
                    return False

                # 降低质量继续尝试
                quality -= 5

    except Exception as e:
        logger.error(f"压缩图片时出错: {str(e)}")
        return False


def convert_image_format(image_path: str, target_format: str = "JPEG") -> bool:
    """Convert image to supported format

    Args:
        image_path: Path to the image file
        target_format: Target format (JPEG/PNG)

    Returns:
        bool: True if conversion was successful
    """
    try:
        with Image.open(image_path) as img:
            # 如果是PNG且有透明通道，优先转换为PNG
            if img.mode == "RGBA" and target_format.upper() == "JPEG":
                target_format = "PNG"

            # 创建新的文件名
            base_path = os.path.splitext(image_path)[0]
            new_path = f"{base_path}.{target_format.lower()}"

            # 转换格式
            if target_format.upper() == "JPEG":
                # 将RGBA转换为RGB（去除透明通道）
                if img.mode == "RGBA":
                    img = img.convert("RGB")

            # 保存新格式的图片
            img.save(new_path, target_format)

            # 如果新文件路径与原文件不同，删除原文件
            if new_path != image_path:
                os.remove(image_path)

            logger.info(f"图片格式转换成功: {image_path} -> {new_path}")
            return True

    except Exception as e:
        logger.error(f"转换图片格式时出错: {str(e)}")
        return False


def resize_image(image_path: str, max_dimension: int = 2000) -> bool:
    """Resize image if dimensions exceed limit

    Args:
        image_path: Path to the image file
        max_dimension: Maximum allowed dimension in pixels

    Returns:
        bool: True if resize was successful
    """
    try:
        with Image.open(image_path) as img:
            width, height = img.size

            # 检查是否需要调整大小
            if width <= max_dimension and height <= max_dimension:
                return True

            # 计算新的尺寸
            if width > height:
                new_width = max_dimension
                new_height = int(height * (max_dimension / width))
            else:
                new_height = max_dimension
                new_width = int(width * (max_dimension / height))

            # 调整图片大小
            resized_img = img.resize((new_width, new_height), Image.LANCZOS)

            # 保存调整后的图片
            resized_img.save(image_path, img.format)

            logger.info(
                f"图片尺寸调整成功: {image_path} "
                f"({width}x{height} -> {new_width}x{new_height})"
            )
            return True

    except Exception as e:
        logger.error(f"调整图片尺寸时出错: {str(e)}")
        return False


def optimize_image(image_path: str) -> bool:
    """Optimize image to meet all requirements

    Args:
        image_path: Path to the image file

    Returns:
        bool: True if all optimizations were successful
    """
    try:
        # 1. 调整尺寸（如果需要）
        if not resize_image(image_path):
            return False

        # 2. 转换格式（如果需要）
        with Image.open(image_path) as img:
            format = img.format
            if format not in ["JPEG", "PNG"]:
                if not convert_image_format(image_path):
                    return False

        # 3. 压缩大小（如果需要）
        if not compress_image(image_path):
            return False

        return True

    except Exception as e:
        logger.error(f"优化图片时出错: {str(e)}")
        return False
